<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * 活动礼物模型
 */
class AnswerActivityGift extends BaseModel
{
    use HasFactory;


    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'answer_activity_gift';


    /*关联活动单位*/
    public function conUnit()
    {
        return $this->hasOne(AnswerActivityUnit::class, 'id', 'unit_id');
    }


    /**
     * 是否配置礼物
     * @param act_id 
     */
    public static function isHaveGift($act_id)
    {
        $gift_info = self::where('act_id', $act_id)->where('is_del', 1)->first();
        if (empty($gift_info)) {
            return '未配置发放礼品，请先配置';
        }
        return true;
    }


    /**
     * 获取单位列表
     * @param act_id 活动id
     */
    public function getUnitList($act_id)
    {
        $res = $this->select('id', 'unit_id', 'act_id')
            ->with(['conUnit' => function ($query) {
                $query->select('id', 'act_id', 'name');
            }])->where('act_id', $act_id)
            ->where('is_del', 1)
            ->groupBy('unit_id')
            ->get()
            ->toArray();

        foreach ($res as $key => $val) {
            if (empty($val['unit_id'])) {
                $res[$key]['id'] = 0;
                $res[$key]['act_id'] = $val['act_id'];
                $res[$key]['name'] = config('other.unit_name');
            } else {
                $res[$key]['id'] = $val['con_unit']['id'];
                $res[$key]['act_id'] = $val['act_id'];
                $res[$key]['name'] = $val['con_unit']['name'];
            }
            unset($res[$key]['con_unit']);
        }
        return $res;
    }
    /**
     * 获取奖品数量
     * @param act_id 活动id
     * @param type 1文化红包 2精美礼品
     * @param unit_id 单位id  0 表示系统单位
     */
    public function getGiftNumber($act_id, $type = null, $unit_id = 0)
    {
        $res = $this->select('id', DB::raw("sum(total_number) as total_number"), DB::raw("sum(use_number) as use_number"))
            ->where(function ($query) use ($unit_id) {
                //false 全查询
                if ($unit_id) {
                    $query->where('unit_id', $unit_id);
                } elseif ($unit_id === 0 || $unit_id === '0') {
                    $query->OrwhereNull('unit_id')->Orwhere('unit_id', 0);
                }
            })->where(function ($query) use ($type) {
                //false 全查询
                if ($type) {
                    $query->where('type', $type);
                }
            })->where('act_id', $act_id)
            ->where('is_del', 1)
            ->get()
            ->toArray();

        return $res;
    }

    /**
     * 获取现在还剩余的可中奖的奖品
     * @param act_id 活动id
     * @param type 1文化红包 2精美礼品
     * @param unit_id 单位id  若单位为空  则，只查询系统数据，若单位不为空，则查询 单位数据 + 系统数据   $unit_id 为 false 则不分单位查询
     */
    public function getSurplusGift($act_id, $type = null, $unit_id = false)
    {
        $res = $this->select('id', 'act_id', 'unit_id', 'name', 'img', 'total_number', 'price', 'use_number', 'percent', 'type', 'way')
            ->where(function ($query) use ($unit_id) {
                //false 全查询
                if ($unit_id !== false) {
                    if ($unit_id) {
                        $unit_id = !is_array($unit_id) ? explode(',', $unit_id) : $unit_id;
                        $query->OrwhereIn('unit_id', $unit_id)->OrwhereNull('unit_id')->Orwhere('unit_id', 0);
                    } else {
                        $query->OrwhereNull('unit_id')->Orwhere('unit_id', 0);
                    }
                }
            })->where(function ($query) use ($type) {
                //false 全查询
                if ($type) {
                    $query->where('type', $type);
                }
            })->where('act_id', $act_id)
            ->whereColumn('total_number', '>', 'use_number') //这里必须使用 whereColumn 否则无效
            ->where('is_del', 1)
            ->orderByDesc('percent')
            ->get()
            ->toArray();

        $data = [];
        if ($res) {
            //再次比较大小
            foreach ($res as $key => $val) {
                if ($val['total_number'] > $val['use_number']) {
                    $data[] = $val;
                }
            }
        }

        return $data;
    }

    /**
     * 获取公示列表
     * @param field int 获取字段信息  数组
     * @param act_id int 活动id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param unit_id int 区域id
     * @param type int 0或空表示  1文化红包 2精美礼品
     * @param way int 0或空表示  领取方式   1 自提  2邮递   红包无此选项
     * @param start_time datetime 创建时间范围搜索(开始) 
     * @param end_time datetime 创建时间范围搜索(结束) 
     * @param keywords string 搜索关键词(类型名称)
     */
    public function lists($field, $act_id, $keywords, $unit_id, $type, $way, $start_time, $end_time, $page, $limit)
    {
        if (empty($field)) {
            $field = [
                'id', 'act_id', 'unit_id', 'name', 'img', 'intro', 'total_number', 'price', 'use_number', 'percent', 'type', 'way', 'start_time', 'end_time', 'tel', 'contacts', 'province', 'city', 'district', 'address', 'remark', 'create_time'
            ];
        }
        $res = $this->select($field)
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('name', 'like', '%' . $keywords . '%');
                }
            })->where(function ($query) use ($act_id, $unit_id, $type, $way, $start_time, $end_time) {
                if ($act_id) {
                    $query->where('act_id', $act_id);
                }
                if ($type) {
                    $query->where('type', $type);
                }
                if ($way) {
                    $query->where('way', $way);
                }
                if ($unit_id) {
                    $query->where('unit_id', $unit_id);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })
            ->with('conUnit')
            ->where('is_del', 1)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        $controllerObj = new Controller();
        $res = $controllerObj->disPageData($res);

        return $res;
    }

    /**
     * 获取单位详情
     * @param act_id int 活动id
     */
    public function detail($id, $field = [])
    {
        if (empty($field)) {
            $field = [
                'id', 'act_id', 'unit_id', 'name', 'img', 'intro', 'total_number', 'price', 'use_number', 'percent', 'type', 'way', 'start_time', 'end_time', 'tel', 'contacts', 'province', 'city', 'district', 'address', 'remark', 'create_time'
            ];
        }
        $res = $this->select($field)
            ->with('conUnit')
            ->where('is_del', 1)
            ->where('id', $id)
            ->first();

        //获取单位区域
        if (!empty($res)) {
            $res['unit_name'] = !empty($res['conUnit']['name']) ?  $res['conUnit']['name'] : '';
            unset($res['conUnit']);
        }

        return $res;
    }

    /**
     * 判断是否存在邮递的礼物
     * @param act_id
     */
    public function isExistsSendGift($act_id)
    {
        $res = $this->where('act_id', $act_id)->where('way', 2)->where('is_del', 1)->first();
        if (empty($res)) {
            return false;
        }
        return true;
    }


    /**
     * 判断是否允许添加礼物 或 查询礼物
     * @param act_id
     */
    public function isAllowAddGift($act_id)
    {
        $res = AnswerActivity::where('id', $act_id)->where('is_del', 1)->value('prize_form'); //获奖情况  1 排名  2 抽奖
        if (empty($res)) {
            return '此活动不存在';
        }
        if ($res != 2) {
            return '此活动不是奖品类型活动';
        }
        return true;
    }

    /**
     * 判断如果是自提礼物，自提点不能为空
     * @param  $data 数据
     */
    public function pickInfoIsFull($data)
    {
        if ($data['way'] != 1) {
            return true;
        }
        if (empty($data['start_time']) || empty($data['end_time'])) {
            return '自提时间不能为空';
        }

        if (empty($data['province']) || empty($data['city']) || empty($data['district']) || empty($data['address'])) {
            return '自提地址不能为空';
        }
        return true;
    }
}
